#!/usr/bin/python

# pip install pymysql
import pymysql
from libs.Config import Config
import config.config
config = Config()

class PythonMysql:
    db = None
    cursor = None

    def connect(self, db_config):
        # 打开数据库连接
        self.db = pymysql.connect(host=db_config['host'],
                                  user=db_config['user'],
                                  password=db_config['password'],
                                  port=db_config['port'],  # 端口
                                  database=db_config['database'],
                                  charset=db_config['charset'])
        # 创建游标
        self.cursor = self.db.cursor()

    def execute_sql(self, sql):
        # 操作数据库
        try:
            tmp_res = self.cursor.execute(sql)
            self.db.commit()
            return tmp_res
        except:
            self.db.rollback()

    def close_db(self):
        # 关闭游标，数据库连接
        self.cursor.close()
        self.db.close()
